using System;
using System.Collections.Generic;

namespace Mgrs
{
    /**消息管理 */
    public class MsgMgr
    {
        private static readonly Dictionary<string, Action<object>> RegisterMsgs = new();

        /**
         * <summary>注册消息</summary>
         * <param name="msgName">注册的消息名</param>
         * <param name="onMsgReceived">注册的消息方法</param>
         */
        public static void RegisterMsg(string msgName, Action<object> onMsgReceived)
        {
            if (!RegisterMsgs.ContainsKey(msgName))
            {
                RegisterMsgs.Add(msgName, _ => { });
            }

            RegisterMsgs[msgName] += onMsgReceived;
        }

        /**
         * <summary>注销消息</summary>
         * <param name="msgName">注销的消息名</param>
         * <param name="onMsgReceived" >注销的消息方法</param>
         */
        public static void UnRegisterMsg(string msgName, Action<object> onMsgReceived = null)
        {
            if (!RegisterMsgs.ContainsKey(msgName))
            {
                return;
            }

            if (onMsgReceived != null)
            {
                RegisterMsgs[msgName] -= onMsgReceived;
            }
            else
            {
                RegisterMsgs.Remove(msgName);
            }
        }

        /**
         * <summary>发送消息</summary>
         * <param name="msgName">发送的消息名</param>
         * <param name="data">发送的数据</param>
         */
        public static void Send(string msgName, object data = null)
        {
            if (RegisterMsgs.ContainsKey(msgName))
            {
                RegisterMsgs[msgName](data);
            }
        }
    }

    /**消息记录 */
    public class MsgRecord
    {
        private static readonly Stack<MsgRecord> MsgRecordPool = new();

        public string MsgName;
        public Action<object> OnMsgReceived;

        /**获取记录对象 */
        public static MsgRecord Allocate(string msgName, Action<object> onMsgReceived)
        {
            MsgRecord record = null;
            record = MsgRecordPool.Count > 0 ? MsgRecordPool.Pop() : new MsgRecord();

            record.MsgName = msgName;
            record.OnMsgReceived = onMsgReceived;
            
            return record;
        }

        /**回收记录对象 */
        public void Recycle()
        {
            MsgName = null;
            OnMsgReceived = null;
            
            MsgRecordPool.Push(this);
        }
    }
}